package test_try;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.util.ArrayList;
import java.util.List;


public class XMLTest02 {
    //创建readXml方法使用dom4j解析XML返回一个List<Book> 对象
    public static void main(String[] args) throws Exception {
        //第二个操作 创建readXml方法使用dom4j解析XML返回一个List<Book> 对象
        List<Book> books = readXml();
        books.forEach(System.out::println);

        writeJson(books);

        writeJsonByJackson(books);
    }
    //第四个操作 把books.json文件 使用jackson输出到控制台
    public static void writeJsonByJackson(List<Book> books) throws IOException {
        // 创建一个ObjectMapper对象
        ObjectMapper mapper = new ObjectMapper();

        // 2.读取books.json文件中的内容
        JsonNode jsonNode = mapper.readTree(new File("day14-code/src/test_try/books.json"));
        for (JsonNode node : jsonNode) {
            System.out.println(node);
        }


    }

    //使用fastjson将List<Book>对象转成JSON字符串
    public static void writeJson(List<Book> books) throws IOException {
        //第三个操作 将以上对象转成JSON字符串写到当前目录下的books.json文件中

        // 1. 将List<Book>对象转成JSON字符串
        String s = JSON.toJSONString(books);
        BufferedWriter bw = new BufferedWriter(new FileWriter("day14-code/src/test_try/books.json"));
        bw.write(s);
        bw.close();
    }


    // 使用dom4j解析XML
    public static List<Book> readXml() throws Exception {
        List<Book> books = new ArrayList<>();
        //创建解析器
        SAXReader reader = new SAXReader();
        //创建文件
        Document document = reader.read("day14-code/src/test_try/xml.xml");
        //3.获取根元素标签
        Element rootElement = document.getRootElement();
        //4.获取所有子元素标签
        List<Element> elements = rootElement.elements();
        for (Element element : elements) {
            Book book = new Book();
            book.setName(element.elementText("title"));
            book.setAuthor(element.elementText("author"));
            book.setPrice(Double.parseDouble(element.elementText("price")));
            books.add(book);
        }
        return books;
//        return elements.stream().map(element -> {
//            Book book = new Book();
//            book.setName(element.elementText("title"));
//            book.setAuthor(element.elementText("author"));
//            book.setPrice(Double.parseDouble(element.elementText("price")));
//            return book;
//        }).toList();
    }
}
